'use strict';

const { DataTypes } = require('sequelize');
const sequelize = require('../../database/sequelize');
const User = require('./user');
const TravelPlan = require('./travel_plan');

const Route = sequelize.define(
    'Route',
    {
        id: {
            type: DataTypes.INTEGER.UNSIGNED,
            primaryKey: true,
            autoIncrement: true,
            comment: '路线ID',
        },
        user_id: {
            type: DataTypes.INTEGER.UNSIGNED,
            allowNull: false,
            comment: '所属用户ID',
        },
        travel_plan_id: {
            type: DataTypes.INTEGER.UNSIGNED,
            allowNull: true,
            comment: '关联旅行计划ID',
        },
        daily_plan_id: {
            type: DataTypes.STRING(50),
            allowNull: true,
            comment: '关联每日计划ID',
        },
        title: {
            type: DataTypes.STRING(100),
            allowNull: false,
            comment: '路线标题',
        },
        routes_data: {
            type: DataTypes.TEXT,
            allowNull: false,
            comment: '路线数据(JSON字符串)',
        },
    },
    {
        tableName: 'routes',
        timestamps: true,
        createdAt: 'created_at',
        updatedAt: 'updated_at',
        underscored: true,
    }
);

Route.belongsTo(User, { foreignKey: 'user_id', as: 'user' });
Route.belongsTo(TravelPlan, { foreignKey: 'travel_plan_id', as: 'plan' });

// 初始化表与开发环境种子数据
(async () => {
    try {
        await Route.sync({ alter: true });
        console.log('✅ 路线表同步成功');
    } catch (e) {
        console.error('路线表初始化失败:', e);
    }
})();

module.exports = Route;